/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestResult;

public class ExtendedTestResult extends TestResult {
	private final Set<String> successes = new HashSet<String>();

	@SuppressWarnings("unchecked")
	public boolean containsError(String testName) {
		return problemsContain(errors(), testName);
	}

	@SuppressWarnings("unchecked")
	public boolean containsFailure(String testName) {
		return problemsContain(failures(), testName);
	}

	public boolean containsSuccess(String testName) {
		return successes.contains(testName);
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// TestResult methods
	///////////////////////////////////////////////////////////////////////////////////////////////
	
	@Override
	public void startTest(Test test) {
		successes.add(getName(test));

		super.startTest(test);
	}

	@Override
	public synchronized void addError(Test test, Throwable t) {
		successes.remove(getName(test));

		super.addError(test, t);
	}

	@Override
	public synchronized void addFailure(Test test, AssertionFailedError t) {
		successes.remove(getName(test));

		super.addFailure(test, t);
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation
	///////////////////////////////////////////////////////////////////////////////////////////////

	private boolean problemsContain(Enumeration<TestFailure> problems, String testName) {
		while (problems.hasMoreElements()) {
			String problematicTestName = getName(problems.nextElement().failedTest());

			if (testName.equals(problematicTestName)) {
				return true;
			}
		}

		return false;
	}

	private String getName(Test test) {
		String testName = ((TestCase) test).getName();

		if (testName.indexOf('(') > -1) {
			testName = testName.substring(0, testName.indexOf('('));
		}

		return testName;
	}
}
